package com.gitee.mrj.aiboot.core.sf.generators.ui.widget;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gitee.mrj.aiboot.annotation.config.KV;
import com.gitee.mrj.aiboot.annotation.config.sf.ui.widget.SFObjectWidget;
import com.gitee.mrj.aiboot.core.sf.generators.FormDefinitionGenerator;
import com.gitee.mrj.aiboot.core.sf.generators.UIForm;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class SFObjectWidgetGenerator implements FormDefinitionGenerator {
    @Override
    public void generate(UIForm root, Field field, UIForm node) {
        SFObjectWidget objectWidget = AnnotatedElementUtils.findMergedAnnotation(field, SFObjectWidget.class);
        generate(node, objectWidget);
    }

    @Override
    public void generate(UIForm node, Class clazz) {
        SFObjectWidget objectWidget = AnnotatedElementUtils.findMergedAnnotation(clazz, SFObjectWidget.class);
        generate(node, objectWidget);
    }

    private void generate(UIForm node, SFObjectWidget objectWidget) {
        ObjectNode ui = node.getUi();

        ui.put("showTitle", objectWidget.showTitle());
        if (objectWidget.card()) {
            ui.put("showExpand", objectWidget.showExpand());
            ui.put("expand", objectWidget.expand());
            ui.put("type", "card");
            ui.put("cardSize", objectWidget.cardSize().value());
            ui.put("cardBorderless", objectWidget.cardBorderless());
            KV[] kvs = objectWidget.cardBodyStyle();
            if (ArrayUtils.isNotEmpty(kvs)) {
                ObjectNode obj = ui.putObject("cardBodyStyle");
                for (KV kv : kvs) {
                    obj.put(kv.key(), kv.value());
                }
            }
        }


    }


    @Override
    public Class[] supports() {
        return new Class[]{SFObjectWidget.class};
    }
}
